package com.shouer.doc.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.shouer.doc.R;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.ApkUtil;
import com.shouer.doc.common.util.FileUtil;
import com.shouer.doc.common.util.SdCardUtils;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.FileUtil;
import com.shouer.doc.common.util.SdCardUtils;
import com.shouer.doc.ui.splash.response.VersionUpdateResponse;

import java.io.File;

/**
 * Created by apple on 15/9/22.
 */
public class UploadService extends Service {

    private boolean isDownloading = false;

    private VersionUpdateResponse versionInfo;
    private DownloadManager mDownloadManager;
    private DownloadManagerPro downloadManagerPro;
    private CompleteReceiver completeReceiver;
    private long downloadId;

    private DownLoadManager downLoadManager;


    @Override
    public void onCreate() {
        super.onCreate();
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        downloadManagerPro = new DownloadManagerPro(mDownloadManager);
        completeReceiver = new CompleteReceiver();
        registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        downLoadManager = new DownLoadManager();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        versionInfo = (VersionUpdateResponse) intent.getSerializableExtra("versionInfo");
        return downLoadManager;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(completeReceiver);
    }

    public class DownLoadManager extends Binder {

        private int currentPercent = 0;

        public void startDownLoadApk() {

            Log.i(DownLoadManager.class.getSimpleName(),"---------------------startDownLoadApk");
            Log.i(DownLoadManager.class.getSimpleName(),"---------------------startDownLoadApk");
            if (versionInfo != null) {
                if (SdCardUtils.isSDCardAvailable()) {
                    File downLoadPathFile = new File(FileUtil.connectFilePath(SdCardUtils.getSDCardPath(), ShouerConst.APK_DOWNLOAD_PATH));
                    if (!downLoadPathFile.exists())
                        downLoadPathFile.mkdirs();
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionInfo.getAppPath()));
                    request.setDestinationInExternalPublicDir(ShouerConst.APK_DOWNLOAD_PATH, versionInfo.getAppFileName());
                    request.allowScanningByMediaScanner();//允许MediaScanner扫描到这个文件，默认不允
                    request.setTitle(getResources().getString(R.string.app_name));//设置下载中通知栏提示的标题
                    request.setDescription("版本更新下载");

                    downloadId = mDownloadManager.enqueue(request);
                }


            }


        }

        public boolean isDownLoadingApk() {
            return isDownloading;
        }

        public int getCurrentPercent() {
            return currentPercent;
        }

        public void setCurrentPercent(int currentPercent) {
            this.currentPercent = currentPercent;
        }
    }


    /**
     * 下载完全结束
     */
    /**
     * @Override public void OnDownloadCompleted(Task task) {
     * isDownloading = false;
     * downloadNotification.removeNotification();
     * String apkSdPath = FileUtil.connectFilePath(PathUtil.APK_DOWNLOAD_PATH, versionInfo.getAppFileName());
     * File apkFile = new File(FileUtil.connectFilePath(SdCardUtils.getSDCardPath(), apkSdPath));
     * <p>
     * if (apkFile.exists()) {
     * boolean isOk = ApkUtil.checkApkFile(UploadService.this, apkFile.getAbsolutePath());
     * if (isOk)
     * ApkUtil.install(UploadService.this, apkFile);
     * }
     * <p>
     * }
     **/

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(CompleteReceiver.class.getSimpleName(),"---------------------onReceive");
            Log.i(CompleteReceiver.class.getSimpleName(),"---------------------onReceive");
            /**
             * get the id of download which have download success, if the id is my id and it's status is successful,
             * then install it
             **/
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == downloadId) {
                // if download successful, install apk
                if (downloadManagerPro.getStatusById(downloadId) == DownloadManager.STATUS_SUCCESSFUL) {
                    String apkSdPath = FileUtil.connectFilePath(ShouerConst.APK_DOWNLOAD_PATH, versionInfo.getAppFileName());
                    File apkFile = new File(FileUtil.connectFilePath(SdCardUtils.getSDCardPath(), apkSdPath));
                    if (apkFile.exists()) {
                        boolean isOk = ApkUtil.checkApkFile(UploadService.this, apkFile.getAbsolutePath());
                        if (isOk)
                            ApkUtil.install(UploadService.this, apkFile);

                    }
                }
            }
        }
    }
}
